package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.exception.ServiceException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AttendanceRecordsMapper;
import com.ruoyi.system.domain.AttendanceRecords;
import com.ruoyi.system.service.IAttendanceRecordsService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 考勤记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-21
 */
@Service
public class AttendanceRecordsServiceImpl implements IAttendanceRecordsService 
{
    private static final Logger log = LoggerFactory.getLogger(AttendanceRecordsServiceImpl.class);

    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;

    /**
     * 查询考勤记录
     * 
     * @param id 考勤记录主键
     * @return 考勤记录
     */
    @Override
    public AttendanceRecords selectAttendanceRecordsById(Long id)
    {
        return attendanceRecordsMapper.selectAttendanceRecordsById(id);
    }

    /**
     * 查询考勤记录列表
     * 
     * @param attendanceRecords 考勤记录
     * @return 考勤记录
     */
    @Override
    public List<AttendanceRecords> selectAttendanceRecordsList(AttendanceRecords attendanceRecords)
    {
        return attendanceRecordsMapper.selectAttendanceRecordsList(attendanceRecords);
    }

    /**
     * 新增考勤记录
     * 
     * @param attendanceRecords 考勤记录
     * @return 结果
     */
    @Override
    public int insertAttendanceRecords(AttendanceRecords attendanceRecords)
    {
        return attendanceRecordsMapper.insertAttendanceRecords(attendanceRecords);
    }

    /**
     * 修改考勤记录
     * 
     * @param attendanceRecords 考勤记录
     * @return 结果
     */
    @Override
    public int updateAttendanceRecords(AttendanceRecords attendanceRecords)
    {
        return attendanceRecordsMapper.updateAttendanceRecords(attendanceRecords);
    }

    /**
     * 批量删除考勤记录
     * 
     * @param ids 需要删除的考勤记录主键
     * @return 结果
     */
    @Override
    public int deleteAttendanceRecordsByIds(Long[] ids)
    {
        return attendanceRecordsMapper.deleteAttendanceRecordsByIds(ids);
    }

    /**
     * 删除考勤记录信息
     * 
     * @param id 考勤记录主键
     * @return 结果
     */
    @Override
    public int deleteAttendanceRecordsById(Long id)
    {
        return attendanceRecordsMapper.deleteAttendanceRecordsById(id);
    }

    @Override
    public List<Map<String, Object>> getTodayCheckInStats() {
        return attendanceRecordsMapper.getTodayCheckInStats();
    }

    @Override
    public List<AttendanceRecords> getMonthRecordsById(Long userId) {
        return attendanceRecordsMapper.getMonthRecordsById(userId);
    }

    /**
     * 导入考勤记录数据

     * @return 导入结果提示信息
     */
    @Override
    public void importRecords(MultipartFile file) throws Exception {
        List<AttendanceRecords> recordsList = readExcel(file);
        validateRecords(recordsList);
        saveRecords(recordsList);
    }

    private List<AttendanceRecords> readExcel(MultipartFile file) throws IOException {
        List<AttendanceRecords> recordsList = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    AttendanceRecords records = new AttendanceRecords();
                    records.setUserId(getCellValueAsLong(row.getCell(0)));
                    records.setWorkDate(getCellValueAsDate(row.getCell(1)));
                    records.setCheckInTime(getCellValueAsDate(row.getCell(2)));
                    records.setCheckOutTime(getCellValueAsDate(row.getCell(3)));
                    records.setCheckInMethod(getCellValueAsString(row.getCell(4)));
                    records.setCheckOutMethod(getCellValueAsString(row.getCell(5)));
                    records.setStatus(getCellValueAsString(row.getCell(6)));
                    records.setReminded(getCellValueAsInteger(row.getCell(7)));
                    records.setNotes(getCellValueAsString(row.getCell(8)));
                    records.setCreatedTime(getCellValueAsDate(row.getCell(9)));
                    records.setUpdatedTime(getCellValueAsDate(row.getCell(10)));
                    records.setUserName(getCellValueAsString(row.getCell(11)));
                    recordsList.add(records);
                }
            }
        }
        return recordsList;
    }

    private Long getCellValueAsLong(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.NUMERIC) {
            return (long) cell.getNumericCellValue();
        }
        return null;
    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        }
        return null;
    }

    private Date getCellValueAsDate(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            return cell.getDateCellValue();
        }
        return null;
    }

    private Integer getCellValueAsInteger(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.NUMERIC) {
            return (int) cell.getNumericCellValue();
        }
        return null;
    }

    private void validateRecords(List<AttendanceRecords> recordsList) throws Exception {
        List<String> errorMessages = new ArrayList<>();
        for (AttendanceRecords records : recordsList) {
            if (records.getUserId() == null || records.getWorkDate() == null) {
                errorMessages.add("记录为空，跳过导入：" + records);
            }
            // 其他验证逻辑可在此处扩展，例如日期格式检查、打卡方式合法性检查等
            if (records.getCheckInTime() != null && records.getCheckOutTime() != null && records.getCheckInTime().after(records.getCheckOutTime())) {
                errorMessages.add("第 " + recordsList.indexOf(records) + " 条记录上班打卡时间不能晚于下班打卡时间：" + records);
            }
        }
        if (!errorMessages.isEmpty()) {
            StringBuilder sb = new StringBuilder("很抱歉，导入失败！共 " + errorMessages.size() + " 条数据格式不正确，错误如下：<br/>");
            for (int i = 0; i < errorMessages.size(); i++) {
                sb.append(i + 1).append("、").append(errorMessages.get(i)).append("<br/>");
            }
            throw new ServiceException(sb.toString());
        }
    }

    private void saveRecords(List<AttendanceRecords> recordsList) {
        for (AttendanceRecords records : recordsList) {
            try {
                attendanceRecordsMapper.insertAttendanceRecords(records);
            } catch (Exception e) {
                log.error("保存考勤记录失败，记录：{}，错误信息：{}", records, e.getMessage());
                throw new ServiceException("保存考勤记录失败：" + e.getMessage());
            }
        }
    }


}
